package customview.ike.com.customviewproject.aop;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ListView;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.ArrayList;
import java.util.List;

import customview.ike.com.customviewproject.aop.RequestPermission.RequestPermission;
import customview.ike.com.customviewproject.utils.permission.PermissionHelper;

/**
 * @author:ike
 * @function: android 6.0 权限请求切面
 * @creat time:16:21 2018/1/30
 **/
@Aspect
public class PermissionAspect {
    private String Tag = "PermissionAspect";
    private String[] requestPermissions;
    /**
     * 拒绝的权限集合
     */
    private List<String> denyPermissions = new ArrayList<>();
    private int requestCode;
    private String[] realRequestPermissions = new String[]{};

    /**
     * requestPermission 为方法参数
     * 创建切点
     * 处理由RequestPermission注解标记的所有方法
     */
    @Pointcut("execution(@customview.ike.com.customviewproject.aop.RequestPermission.RequestPermission * *(..))" +
            "&& @annotation(requestPermission)")
    public void excuteCheckPermission(RequestPermission requestPermission) {

    }

    /**
     * 处理切面
     *
     * @return
     */
    @Around("excuteCheckPermission(requestPermission)")
    public void checkPermission(final ProceedingJoinPoint joinPoint, RequestPermission requestPermission) {
        //android 6.0 以下直接执行
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            excuteOriginMethod(joinPoint);
        } else {
            denyPermissions.clear();
            //进行权限判定
            Object target = joinPoint.getTarget();
            //获取注解信息
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            RequestPermission annotation = signature.getMethod().getAnnotation(RequestPermission.class);
            if (annotation != null) {
                requestPermissions = annotation.value();
                requestCode = annotation.requestCode();
            }
            Activity context = getContext(target);
            for (String permission : requestPermissions) {
                int selfPermission = ContextCompat.checkSelfPermission(context, permission);
                if (selfPermission == PackageManager.PERMISSION_DENIED) {
                    denyPermissions.add(permission);
                }
            }
            //权限全部通过
            if (denyPermissions.isEmpty()) {
                excuteOriginMethod(joinPoint);
                return;
            }
            //申请权限
            if (context != null) {
                if (target instanceof Activity) {
                    Activity activity = (Activity) target;
                    requestPermission(joinPoint, activity);
                } else if (target instanceof Fragment) {
                    Fragment fragment = (Fragment) target;
                    requestPermission(joinPoint, fragment);
                }
            }
        }


    }

    /**
     * 申请权限
     *
     * @param joinPoint 链接点
     * @param object    申请对象
     */
    private void requestPermission(final ProceedingJoinPoint joinPoint, Object object) {
        PermissionHelper.with(object)
                .addRequestPermissions(denyPermissions)
                .addRequestCode(requestCode)
                .addCallBack(new PermissionHelper.PermissionCallBack() {
                    @Override
                    public void requestPermissionSuccess() {
                        excuteOriginMethod(joinPoint);
                        Log.e(Tag, "权限申请成功");
                    }

                    @Override
                    public void requestPermissionFailed(List<String> failGetPermissions) {
                        if (failGetPermissions != null && failGetPermissions.size() > 0) {
                            for (String failGetPermission : failGetPermissions) {
                                Log.e(Tag, "权限被拒绝:" + failGetPermission);
                            }
                        }
                    }
                    
                    @Override
                    public void requestPermissionAlwaysFailed(List<String> alwaysFailPermissions) {
                        if (alwaysFailPermissions != null && alwaysFailPermissions.size() > 0) {
                            for (String failGetPermission : alwaysFailPermissions) {
                                Log.e(Tag, "权限被永远拒绝:" + failGetPermission);
                            }
                        }
                    }
                })
                .request();

    }

    /**
     * 权限验证通过继续执行原来的方法
     *
     * @param joinPoint
     */
    private void excuteOriginMethod(ProceedingJoinPoint joinPoint) {
        try {
            joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 获取上下文
     *
     * @param object
     * @return
     */
    private Activity getContext(Object object) {
        if (object instanceof Activity) {
            return (Activity) object;
        } else if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            return fragment.getActivity();

        }
        return null;
    }
}
